﻿using Abp.Runtime.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using System.Linq;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Web.Authentication.JwtBearer
{
    public class AppJwtBearerEvents : JwtBearerEvents
    {
        /// <summary>
        /// 从URL上获取token
        /// </summary>
        private static Task QueryStringTokenResolver(MessageReceivedContext context)
        {
            if (!context.HttpContext.Request.Path.HasValue)
            {
                // We are just looking for signalr clients
                return Task.CompletedTask;
            }

            var authToken = context.HttpContext.Request.Query[JwtAuthOptions.TokenQueryName].FirstOrDefault();
            if (authToken == null)
            {
                // Cookie value does not matches to querystring value
                return Task.CompletedTask;
            }

            // Set auth token from cookie
            context.Token = authToken;//SimpleStringCipher.Instance.Decrypt(authToken, AppConsts.DefaultPassPhrase);
            return Task.CompletedTask;
        }
        /// <summary>
        /// 从cookie获取token
        /// </summary>
        private static Task CookiesTokenResolver(MessageReceivedContext context)
        {
            if (!context.HttpContext.Request.Path.HasValue)
            {
                return Task.CompletedTask;
            }

            var authToken = context.HttpContext.Request.Cookies[JwtAuthOptions.TokenCookieName];
            if (authToken == null)
            {
                // Cookie value does not matches to querystring value
                return Task.CompletedTask;
            }

            // Set auth token from cookie
            context.Token = authToken;
            return Task.CompletedTask;
        }

        public override async Task MessageReceived(MessageReceivedContext context)
        {
            //如果没有用户授权头,尝试从cookies或者query中获取
            if (!context.Request.Headers.ContainsKey(HeaderNames.Authorization))
            {
                var options = context.HttpContext.RequestServices.GetRequiredService<JwtAuthOptions>();
                if (context.Token == null && options.SupportCookieAuthentication)
                    await CookiesTokenResolver(context);
                if (context.Token == null && options.SupportQueryAuthentication)
                    await QueryStringTokenResolver(context);
            }
        }

        //public override async Task TokenValidated(TokenValidatedContext context)
        //{
        //    //contenxt.SecurityToken
        //    var sigInManager = context.HttpContext.RequestServices.GetRequiredService<SignInManager>();
        //    var user = await sigInManager.ValidateSecurityStampAsync(context.Principal);
        //    if (user == null)
        //        context.Fail("token Expired");
        //}
    }
}
